// components/slider/slider.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    min: {
      type: Number,
      value: 0
    },
    max: {
      type: Number,
      value: 100
    },
    step: {
      type: Number,
      value: 1
    },
    value: {
      type: Number,
      value: 0,
      observer () {
        this.setCurPos()
      }
    },
    disabled: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentPosition: '0%',
    sliderWidth: 0
  },
  ready () {
    var queryHeight = this.createSelectorQuery();
    queryHeight.select('.slider').boundingClientRect();
    queryHeight.exec((res) => {
      this.setData({
        sliderWidth: res[0].width
      })
    })
    // this.setCurPos()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    setCurPos () {
      const { min, max, value } = this.data
      this.setData({
        currentPosition: `${ (value - min) / (max - min) * 100 }%`
      })
    },
    onTouchstart(event) {
      if (this.data.disabled) {
        return
      }
      const {pageX, pageY} = event.touches[0]
      this.dragging = true
      this.isClick = true
      this.startX = pageX
      this.startPosition = parseFloat(this.data.currentPosition)
      this.newPosition = this.startPosition
    },

    onTouchMove(event) {
      if (this.dragging) {
        const {pageX, pageY} = event.touches[0]
        this.isClick = false;
        let diff = 0;
        this.currentX = pageX;
        diff = (this.currentX - this.startX) / this.data.sliderWidth * 100;
        this.newPosition = this.startPosition + diff;
        this.setPosition(this.newPosition);
      }
    },

    onTouchEnd() {
      if (this.dragging) {
        setTimeout(() => {
          this.dragging = false;
          if (!this.isClick) {
            this.setPosition(this.newPosition);
          }
        }, 0);
      }
    },

    setPosition(newPosition) {
      const { min, max, step } = this.data
      if (newPosition === null || isNaN(newPosition)) return;
      if (newPosition < 0) {
        newPosition = 0;
      } else if (newPosition > 100) {
        newPosition = 100;
      }
      const lengthPerStep = 100 / ((max - min) / step);
      const steps = Math.round(newPosition / lengthPerStep);
      let value = parseInt(steps * lengthPerStep * (max - min) * 0.01 + min)
      this.triggerEvent('setValue', { value }, {})
    }
  }
})
